import { defineComponent, ref } from "vue";
import Field from "@/components/Field";
import { Calendar } from "vant";
import { IFormItem, IFormTypeData } from "../../types";
import moment from "moment";
import { IFormCalendar } from "./types";

export default defineComponent({
  name: "select-view",
  props: {
    modelValue: {
      type: String,
      default: "",
    },
    item: {
      type: Object as () => IFormItem & IFormCalendar,
      default: () => {
        return {};
      },
    },
    typeData: {
      type: Array as () => IFormTypeData[],
      default: () => [],
    },
  },
  emits: ["change"],
  setup(props, { emit }) {
    const showModal = ref(false);
    const getDate = () => {
      if (props.item.props?.type == "range") {
        return [
          moment(props.modelValue[0] || moment()).toDate(),
          moment(props.modelValue[1] || moment()).toDate(),
        ];
      } else {
        return moment(props.modelValue || moment()).toDate();
      }
    };
    const getValue = (data: any) => {
      if (props.item.props?.type == "range") {
        return [
          moment(data[0]).format("YYYY-MM-DD"),
          moment(data[1]).format("YYYY-MM-DD"),
        ];
      } else {
        return moment(data).format("YYYY-MM-DD");
      }
    };
    const getName = () => {
      if (Array.isArray(props.modelValue)) {
        return props.modelValue.join("~");
      } else {
        return props.modelValue;
      }
    };
    return () => {
      function renderModal() {
        return (
          <Calendar
            v-model:show={showModal.value}
            teleport="body"
            type={props.item.props?.type}
            defaultDate={getDate()}
            onConfirm={(data) => {
              emit("change", getValue(data));
              showModal.value = false;
            }}
          />
        );
      }
      return (
        <div>
          <Field
            name={getName()}
            onClick={() => (showModal.value = true)}
            isLink={true}
          />
          {renderModal()}
        </div>
      );
    };
  },
});
